package com.suixinsanren.design.command.demo04;

public class RemoteControl {

    private final Command[] onCommands;
    private final Command[] offCommands;
    private final int MAX_SLOT;
    private Command undo;

    public RemoteControl(int slot) {
        onCommands = new Command[slot];
        offCommands = new Command[slot];
        undo = new NoCommand();
        MAX_SLOT = slot;
    }

    public void setCommand(int slot, Command onCommand, Command offCommand) {
        checkSlot(slot);
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }

    public void onButtonWasPushed(int slot) {
        checkSlot(slot);
        onCommands[slot].execute();
        undo = onCommands[slot];
    }

    public void offButtonWasPushed(int slot) {
        checkSlot(slot);
        offCommands[slot].execute();
        undo = offCommands[slot];
    }

    public void undo() {
        undo.undo();
    }

    public void checkSlot(int slot) {
        if (slot >= MAX_SLOT || slot < 0) {
            throw new IllegalArgumentException("没有该槽位");
        }
    }
}
